#include "histogramdialog.h"
#include "resource.h"

#include <algorithm>

using std::vector;

HistogramDialog::HistogramDialog()
	: Dialog( MAKEINTRESOURCE( IDD_DIALOG_HISTOGRAM ) )
{
	_dib = NULL;
}

void HistogramDialog::setDIB( DIB *dib )
{
	_dib = dib;
}

BOOL HistogramDialog::handleMessage( UINT uMsg, WPARAM wParam, LPARAM lParam )
{
	switch( uMsg )
	{
	case WM_INITDIALOG:
		{
			getHistogramValues();
		}
		break;
	case WM_COMMAND:
		switch( LOWORD( wParam ) )
		{
		case IDOK:
		case IDCANCEL:
			//Close the dialog.
			EndDialog( hWnd(), LOWORD( wParam ) );

			//Return TRUE because the dialog should not handle any more messages.
			return TRUE;
		}
		break;
	case WM_PAINT:
		PAINTSTRUCT ps;
		HDC hDC = BeginPaint( hWnd(), &ps );

		//Paint a border.
		MoveToEx( hDC, 10, 10, NULL );
		LineTo( hDC, 267, 10 );
		LineTo( hDC, 267, 111 );
		LineTo( hDC, 10, 111 );
		LineTo( hDC, 10, 10 );

		//Get the maximum value in the graph.
		unsigned int max = *std::max_element<vector<unsigned int>::iterator>( _values.begin(), _values.end() );

		if( max > 0 )
		{
			//Paint the graph.
			for( unsigned int i = 0; i < 256; ++i )
			{
				MoveToEx( hDC, i + 11, 110, NULL );
				LineTo( hDC, i + 11, 110 - ( _values[i] * 100 / max ) );
			}
		}

		EndPaint( hWnd(), &ps );
		break;
	}
	//This return value will execute the normal operations (as defined in win32) for
	//the message.
	return FALSE;
}

void HistogramDialog::getHistogramValues()
{
	//We need to store 256 numbers in the vector.
	_values.resize( 256 );
	for( unsigned int i = 0; i < 256; ++i )
	{
		//Reset each value to zero.
		_values[i] = 0;
	}

	if( _dib )
	{
		//Get an image description to access the bitmap data more easily.
		Image image = _dib->getImage( NULL );

		//TODO: Read each pixel in image and add 1 to the corresponding value
		//      in the values vector.
	}
}
